﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using MasterDetailTemplate.Models;
using SQLite;

namespace MasterDetailTemplate.Services.impl
{
    public class FavoriteStorageService : IFavoriteStorageService {
        public const string DbName = "favorite.db";

        public static readonly string DBPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);

        private IPreferenceStorage _preference;

        private SQLiteAsyncConnection _connection;

        public SQLiteAsyncConnection Connection =>
            _connection ?? (_connection = new SQLiteAsyncConnection(DBPath));

        public async Task InitializeAsync() {
            await Connection.CreateTableAsync<Favorite>();
            _preference.Set(FavoriteStorageConstants.VersionKey,
                FavoriteStorageConstants.VERSION);
        }

        public bool IsInitialized() =>
            _preference
                .Get(FavoriteStorageConstants.VersionKey,
                    FavoriteStorageConstants.DEFAULTVERSION)
                .Equals(FavoriteStorageConstants.VERSION);

        public async Task<Favorite> getFavoriteAsync(int dietId) =>
            await Connection.Table<Favorite>()
                .FirstOrDefaultAsync(p => p.DietId == dietId);

        public async Task refreshFavorite(Favorite favorite) =>
            await _connection.InsertOrReplaceAsync(favorite);

        public async Task<List<Favorite>> GetFavoritesAsync() =>
            await _connection.Table<Favorite>().ToListAsync();
        public async Task CloseConnection()
        {
            await _connection.CloseAsync();
            _connection = null;
        }

        public FavoriteStorageService(IPreferenceStorage preference) {
            _preference = preference;
        }
    }
}
